﻿namespace DomainServices.Tools.SharedTypes
{
    using DomainServices.Tools;
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.ServiceModel.DomainServices;

    internal class SharedAssemblies
    {
        private List<Assembly> _assemblies;
        private List<string> _assemblyFileNames;
        private IEnumerable<string> _assemblySearchPaths;
        private ILogger _logger;
        private ConcurrentDictionary<string, Type> _sharedTypeByName = new ConcurrentDictionary<string, Type>(StringComparer.OrdinalIgnoreCase);

        internal SharedAssemblies(IEnumerable<string> assemblyFileNames, IEnumerable<string> assemblySearchPaths, ILogger logger)
        {
            if (assemblyFileNames == null)
            {
                throw new ArgumentNullException("assemblyFileNames");
            }
            this._logger = logger;
            this._assemblyFileNames = new List<string>(assemblyFileNames);
            this._assemblySearchPaths = assemblySearchPaths ?? ((IEnumerable<string>) new string[0]);
        }

        private static Type EquivalentMsCorlibType(Type type)
        {
            if (!AssemblyUtilities.IsAssemblyMsCorlib(type.Assembly.GetName()))
            {
                return null;
            }
            if (!System.ServiceModel.DomainServices.TypeUtility.IsPredefinedType(type))
            {
                return null;
            }
            return type;
        }

        private MethodBase FindSharedMethodOrConstructor(Type sharedType, CodeMemberKey key)
        {
            Type[] sharedTypes = this.GetSharedTypes(key.ParameterTypeNames);
            if (sharedTypes != null)
            {
                bool isConstructor = key.IsConstructor;
                IEnumerable<MethodBase> enumerable = isConstructor ? sharedType.GetConstructors().Cast<MethodBase>() : sharedType.GetMethods().Cast<MethodBase>();
                foreach (MethodBase base2 in enumerable)
                {
                    if (!isConstructor && !string.Equals(base2.Name, key.MemberName, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                    ParameterInfo[] parameters = base2.GetParameters();
                    if (parameters.Length == sharedTypes.Length)
                    {
                        int num = 0;
                        for (int i = 0; i < parameters.Length; i++)
                        {
                            if (!string.Equals(parameters[i].ParameterType.FullName, sharedTypes[i].FullName, StringComparison.OrdinalIgnoreCase))
                            {
                                break;
                            }
                            num++;
                        }
                        if (num == parameters.Length)
                        {
                            return base2;
                        }
                    }
                }
            }
            return null;
        }

        private Type FindSharedType(string typeName)
        {
            Type type = Type.GetType(typeName, false);
            if (type != null)
            {
                return this.FindSharedType(type);
            }
            foreach (Assembly assembly in this.Assemblies)
            {
                foreach (Type type2 in AssemblyUtilities.GetExportedTypes(assembly, this._logger))
                {
                    if (string.Equals(typeName, type2.FullName, StringComparison.OrdinalIgnoreCase))
                    {
                        return type2;
                    }
                }
            }
            return null;
        }

        private Type FindSharedType(Type type)
        {
            foreach (Assembly assembly in this.Assemblies)
            {
                foreach (Type type2 in AssemblyUtilities.GetExportedTypes(assembly, this._logger))
                {
                    if (IsSameType(type, type2))
                    {
                        return type2;
                    }
                }
            }
            return EquivalentMsCorlibType(type);
        }

        internal string GetSharedAssemblyPath(CodeMemberKey key)
        {
            string location = null;
            Type sharedType = this.GetSharedType(key.TypeName);
            if (sharedType != null)
            {
                switch (key.KeyKind)
                {
                    case CodeMemberKey.CodeMemberKeyKind.TypeKey:
                        return sharedType.Assembly.Location;

                    case CodeMemberKey.CodeMemberKeyKind.PropertyKey:
                    {
                        PropertyInfo property = sharedType.GetProperty(key.MemberName);
                        if (property != null)
                        {
                            location = property.DeclaringType.Assembly.Location;
                        }
                        return location;
                    }
                    case CodeMemberKey.CodeMemberKeyKind.MethodKey:
                        if (this.GetSharedTypes(key.ParameterTypeNames) != null)
                        {
                            MethodBase base2 = this.FindSharedMethodOrConstructor(sharedType, key);
                            if (base2 != null)
                            {
                                location = base2.DeclaringType.Assembly.Location;
                            }
                        }
                        return location;
                }
            }
            return location;
        }

        internal MethodBase GetSharedMethod(string typeName, string methodName, IEnumerable<string> parameterTypeNames)
        {
            MethodBase base2 = null;
            Type sharedType = this.GetSharedType(typeName);
            if (sharedType != null)
            {
                CodeMemberKey key = CodeMemberKey.CreateMethodKey(typeName, methodName, (parameterTypeNames == null) ? new string[0] : parameterTypeNames.ToArray<string>());
                base2 = this.FindSharedMethodOrConstructor(sharedType, key);
            }
            return base2;
        }

        internal PropertyInfo GetSharedProperty(string typeName, string propertyName)
        {
            PropertyInfo property = null;
            Type sharedType = this.GetSharedType(typeName);
            if (sharedType != null)
            {
                property = sharedType.GetProperty(propertyName);
            }
            return property;
        }

        internal Type GetSharedType(string typeName)
        {
            return this._sharedTypeByName.GetOrAdd(typeName, n => this.FindSharedType(n));
        }

        internal Type GetSharedType(Type type)
        {
            return this._sharedTypeByName.GetOrAdd(type.FullName, n => this.FindSharedType(type));
        }

        internal Type[] GetSharedTypes(IEnumerable<string> typeNames)
        {
            List<Type> list = new List<Type>();
            if (typeNames != null)
            {
                foreach (string str in typeNames)
                {
                    Type item = this.FindSharedType(str);
                    if (item == null)
                    {
                        return null;
                    }
                    list.Add(item);
                }
            }
            return list.ToArray();
        }

        private static bool IsSameType(Type type1, Type type2)
        {
            return type1.FullName.Equals(type2.FullName, StringComparison.Ordinal);
        }

        private void LoadAssemblies()
        {
            this._assemblies = new List<Assembly>();
            Dictionary<string, Assembly> loadedAssemblies = new Dictionary<string, Assembly>();
            foreach (string str in this._assemblyFileNames)
            {
                Assembly item = AssemblyUtilities.ReflectionOnlyLoadFrom(str, this._logger);
                if (item != null)
                {
                    this._assemblies.Add(item);
                    loadedAssemblies[item.FullName] = item;
                }
            }
            foreach (Assembly assembly2 in this._assemblies)
            {
                AssemblyUtilities.ReflectionOnlyLoadReferences(assembly2, this._assemblySearchPaths, loadedAssemblies, true, this._logger);
            }
        }

        private IEnumerable<Assembly> Assemblies
        {
            get
            {
                if (this._assemblies == null)
                {
                    this.LoadAssemblies();
                }
                return this._assemblies;
            }
        }
    }
}

